package cn.itrip.service;

import cn.itrip.commons.Page;
import cn.itrip.dto.HotelPageDTO;
import cn.itrip.vo.HotelListHotelCityVO;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Super God Jie
 * @version 1.0  2022-04-15 08:14
 */
@Service
public class SearchService {

	private static HttpSolrClient httpSolrClient = new HttpSolrClient("http://localhost:8090/solr/hotel");

	static {
		httpSolrClient.setParser(new XMLResponseParser());
		httpSolrClient.setSoTimeout(500);
	}

	public List<HotelListHotelCityVO> searchItripHotelListByHotCity(String cityId,Integer count) throws Exception {
		System.out.println("cityId +\"\\\\\\\\t\"+count = " + cityId + "\\\\t" + count);

		SolrQuery solrQuery = new SolrQuery();
		solrQuery.setQuery("*:*");
		solrQuery.setFilterQueries("cityId:"+cityId);
		solrQuery.setStart(0);
		solrQuery.setRows(count);

		List<HotelListHotelCityVO> beans =
				httpSolrClient.query(solrQuery).getBeans(HotelListHotelCityVO.class);
		return beans;
	}

	public Page<HotelListHotelCityVO> searchItripHotelPage(HotelPageDTO hotelPageDTO) throws Exception {
		System.out.println("hotelPageDTO = " + hotelPageDTO);
		Assert.notNull(hotelPageDTO,"入参不合法");

		SolrQuery query = new SolrQuery();
		if(StringUtils.hasText(hotelPageDTO.getDestination())){
			query.setQuery("destination:"+hotelPageDTO.getDestination());
		}
		if(StringUtils.hasText(hotelPageDTO.getKeywords())){
			String q = query.get("q");
			q += " and keyword:"+hotelPageDTO.getKeywords();
			query.setQuery(q);
		}

		query.setStart((hotelPageDTO.getPageNo() - 1) * hotelPageDTO.getPageSize());
		query.setRows(hotelPageDTO.getPageSize());

		// 设定返回记录数，默认为10条
		QueryResponse response = httpSolrClient.query(query);
		Long numFound = response.getResults().getNumFound();
		Page<HotelListHotelCityVO> page = new Page(hotelPageDTO.getPageNo()
				,numFound.intValue(), hotelPageDTO.getPageSize());

		List<HotelListHotelCityVO> beans = response.getBeans(HotelListHotelCityVO.class);
		page.setRows(beans);
		return page;
	}
}
